package com.yuanqi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.dto.PurchaseReturnOrderDTO;
import com.yuanqi.pojo.PurchaseReturnOrder;
import com.yuanqi.service.PurchaseReturnOrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/sales/return")
public class PurchaseReturnOrderController {

    @Resource
    private PurchaseReturnOrderService purchaseReturnOrderService;

    /**
     * 创建退货订单
     */
    @PostMapping
    public Map<String, Object> createReturnOrder(@RequestBody PurchaseReturnOrderDTO returnOrderDTO) {
        try {
            PurchaseReturnOrderDTO result = purchaseReturnOrderService.createReturnOrder(returnOrderDTO);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", result);
            resp.put("message", "退货订单创建成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "退货订单创建失败：" + e.getMessage());
            return resp;
        }
    }

    /**
     * 更新退货订单
     */
    @PutMapping("/{id}")
    public Map<String, Object> updateReturnOrder(@PathVariable Long id, @RequestBody PurchaseReturnOrderDTO returnOrderDTO) {
        try {
            returnOrderDTO.getReturnOrder().setId(id);
            boolean result = purchaseReturnOrderService.updateReturnOrder(returnOrderDTO);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "退货订单更新成功" : "退货订单更新失败");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "退货订单更新失败：" + e.getMessage());
            return resp;
        }
    }

    /**
     * 获取退货订单详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getReturnOrderDetail(@PathVariable Long id) {
        PurchaseReturnOrderDTO dto = purchaseReturnOrderService.getReturnOrderDetail(id);
        Map<String, Object> resp = new HashMap<>();
        if (dto != null) {
            resp.put("success", true);
            resp.put("data", dto);
        } else {
            resp.put("success", false);
            resp.put("message", "退货订单不存在");
        }
        return resp;
    }

    /**
     * 分页查询退货订单
     */
    @GetMapping("/page")
    public IPage<PurchaseReturnOrderDTO> pageReturnOrders(
            @RequestParam(defaultValue = "1") Long pageNo,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String returnOrderCode,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer status) {
        
        Page<PurchaseReturnOrder> page = new Page<>(pageNo, pageSize);
        return purchaseReturnOrderService.pageReturnOrders(page, returnOrderCode, customerId, status);
    }

    /**
     * 审核退货订单
     */
    @PostMapping("/{id}/approve")
    public Map<String, Object> approveReturnOrder(@PathVariable Long id, @RequestParam(required = false) String approvalRemark) {
        try {
            boolean result = purchaseReturnOrderService.approveReturnOrder(id, approvalRemark);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "退货订单审核通过" : "退货订单审核失败");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "退货订单审核失败：" + e.getMessage());
            return resp;
        }
    }

    /**
     * 拒绝退货订单
     */
    @PostMapping("/{id}/reject")
    public Map<String, Object> rejectReturnOrder(@PathVariable Long id, @RequestParam(required = false) String rejectReason) {
        try {
            boolean result = purchaseReturnOrderService.rejectReturnOrder(id, rejectReason);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "退货订单已拒绝" : "退货订单拒绝失败");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "退货订单拒绝失败：" + e.getMessage());
            return resp;
        }
    }

    /**
     * 处理退货订单
     */
    @PostMapping("/{id}/process")
    public Map<String, Object> processReturnOrder(@PathVariable Long id, @RequestParam(required = false) String processRemark) {
        try {
            boolean result = purchaseReturnOrderService.processReturnOrder(id, processRemark);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "退货订单处理成功" : "退货订单处理失败");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "退货订单处理失败：" + e.getMessage());
            return resp;
        }
    }

    /**
     * 根据销售订单ID查询退货订单
     */
    @GetMapping("/sales-order/{salesOrderId}")
    public Map<String, Object> getReturnOrdersBySalesOrder(@PathVariable Long salesOrderId) {
        List<PurchaseReturnOrder> returnOrders = purchaseReturnOrderService.getReturnOrdersBySalesOrderId(salesOrderId);
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", true);
        resp.put("data", returnOrders);
        resp.put("total", returnOrders.size());
        return resp;
    }

    /**
     * 删除退货订单
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteReturnOrder(@PathVariable Long id) {
        try {
            PurchaseReturnOrder returnOrder = purchaseReturnOrderService.getById(id);
            if (returnOrder == null) {
                Map<String, Object> resp = new HashMap<>();
                resp.put("success", false);
                resp.put("message", "退货订单不存在");
                return resp;
            }
            
            if (returnOrder.getStatus() != 0) {
                Map<String, Object> resp = new HashMap<>();
                resp.put("success", false);
                resp.put("message", "只有待审核状态的退货订单可以删除");
                return resp;
            }
            
            boolean result = purchaseReturnOrderService.removeById(id);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "退货订单删除成功" : "退货订单删除失败");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "退货订单删除失败：" + e.getMessage());
            return resp;
        }
    }

    /**
     * 获取退货订单状态统计
     */
    @GetMapping("/stats")
    public Map<String, Object> getReturnOrderStats() {
        Map<String, Object> resp = new HashMap<>();
        
        // 统计各状态退货订单数量
        long pendingCount = purchaseReturnOrderService.count(
            purchaseReturnOrderService.lambdaQuery().eq(PurchaseReturnOrder::getStatus, 0)
        );
        
        long approvedCount = purchaseReturnOrderService.count(
            purchaseReturnOrderService.lambdaQuery().eq(PurchaseReturnOrder::getStatus, 1)
        );
        
        long processedCount = purchaseReturnOrderService.count(
            purchaseReturnOrderService.lambdaQuery().eq(PurchaseReturnOrder::getStatus, 2)
        );
        
        long rejectedCount = purchaseReturnOrderService.count(
            purchaseReturnOrderService.lambdaQuery().eq(PurchaseReturnOrder::getStatus, 3)
        );
        
        resp.put("success", true);
        resp.put("pendingCount", pendingCount);
        resp.put("approvedCount", approvedCount);
        resp.put("processedCount", processedCount);
        resp.put("rejectedCount", rejectedCount);
        resp.put("totalCount", pendingCount + approvedCount + processedCount + rejectedCount);
        
        return resp;
    }
}








